<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 职称级别
 *
 * @icon fa fa-circle-o
 */
class Grade extends Backend
{

    /**
     * Grade模型对象
     * @var \app\admin\model\pt\Grade
     */
    protected $model = null;

    protected $excludeFields = ['update_time'];

    // 设置selectpage返回的字段
    protected $selectpageFields = 'id,grade_name,grade_code';

    public function _initialize()
    {
        parent::_initialize();
        // $grade_detail_conf = Config::getConfig(null, "job_details", "tabs");
        // $this->view->assign("grade_detail_conf", $grade_detail_conf);
        $this->model = new \app\admin\model\pt\Grade;

    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(["workDetails"])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['grade_name'] = trim($params['grade_name']);
        $params['grade_code'] = trim($params['grade_code']);
        $workDetails = $params['work_details'];
        $workDetails = (array) json_decode($workDetails, true);

        // 验证工作明细数据
        $this->validateWorkDetails($workDetails, null);

        Db::startTrans();
        try {
            $this->model->validateFailException(true)->validate(
                ['grade_name' => ['unique' => 'pt_grade,grade_name']],
                ['grade_name.unique' => '服务名称已经存在，请更换']
            );

            $this->model->allowField(true)->save($params);

            // 👇 关键：手动判断 saveAll 返回值
            $this->model->workDetails()->saveAll($workDetails);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('err:' . $e->getMessage());
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $workDetails = $this->model->workDetails()->where('grade_id', $row['id'])->field("work_detail_name,price_primary,price_secondary,reward_primary,reward_secondary,job_content")->select();
            $workDetails = collection($workDetails)->toArray();
            $workDetails = json_encode($workDetails, JSON_UNESCAPED_UNICODE);
            $this->view->assign('work_details', $workDetails);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['grade_name'] = trim($params['grade_name']);
        $params['grade_code'] = trim($params['grade_code']);
        $params = $this->preExcludeFields($params);

        $workDetails = $params['work_details'];
        $workDetails = (array) json_decode($workDetails, true);
        //设置当前时间,不是时间戳
        $params['update_time'] = date('Y-m-d H:i:s');

        // 验证工作明细数据
        $this->validateWorkDetails($workDetails, $row['id']);
        $result = false;
        Db::startTrans();
        try {
            $row->validateFailException()->validate(
                //'unique' => "表名,字段名,排除ID"
                ['grade_name' => ['unique' => "pt_grade,grade_name,{$row['id']}"]],
                ['grade_name.unique' => '服务名称已经存在，请更换']
            );
            $result = $row->allowField(true)->save($params);
            $row->workDetails()->where('grade_id', $row['id'])->delete();
            $row->workDetails()->saveAll($workDetails);
            Db::commit();

        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            //清理服务细项
            Db::name("pt_work_details")->where('grade_id', 'in', $ids)->delete();

            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }



    /**
     * 验证工作明细数据
     * 
     * @param array $workDetails 工作明细数组
     * @param int $seriesId 系列ID
     * @return void
     * @throws \think\exception\HttpException
     */
    private function validateWorkDetails($workDetails, $gradeId)
    {
        $work_detail_names = [];
        $seq_nos = [];

        foreach ($workDetails as $k => &$v) {
            if (!empty($gradeId)) {
                $v['grade_id'] = $gradeId;
            }


            // 验证序号
            $v['seq_no'] = trim($v['seq_no']);
            if (in_array($v['seq_no'], $seq_nos)) {
                $this->error('服务规格序号【' . $v['seq_no'] . '】不能重复');
            }
            $seq_nos[] = $v['seq_no'];
            if ($v['seq_no'] == '') {
                $this->error('服务规格序号不能为空');
            }

            // 验证工作明细名称
            $v['work_detail_name'] = trim($v['work_detail_name']);
            if (in_array($v['work_detail_name'], $work_detail_names)) {
                $this->error('服务规格名称【' . $v['work_detail_name'] . '】不能重复');
            }
            $work_detail_names[] = $v['work_detail_name'];
            if ($v['work_detail_name'] == '') {
                $this->error('服务规格名称不能为空');
            }

            // 验证价格和公式
            //$this->validatePaymentTypes($v);
        }
    }

    /**
     * 验证支付类型相关字段
     * 
     * @param array $workDetail 工作明细项
     * @return void
     * @throws \think\exception\HttpException
     */
    private function validatePaymentTypes($workDetail)
    {
        // 如果 payment_types 在[1,2]之间,则price_primary 不可以为空
        if ($workDetail['payment_types'] >= 1 && $workDetail['payment_types'] <= 2 && $workDetail['price_primary'] == '') {
            $this->error('服务规格主责价格不能为空');
        }

        // 如果payment_types =3 ,则公式不可以为空（已移除公式字段，此验证暂时保留但不执行）
        // if ($workDetail['payment_types'] == 3 && $workDetail['formula'] == '') {
        //     $this->error('服务规格公式不能为空');
        // }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
